<?php
declare(strict_types=1);

/**
 * Created by hyperf-study.
 * Author: yutlong
 * Email: yut19856@126.com
 * Date: 2020/8/12
 * Time: 16:35
 * Copyright © 2019 - 2020
 */

namespace App\Service;

use App\Job\TestJob;
use Hyperf\AsyncQueue\Annotation\AsyncQueueMessage;
use Hyperf\AsyncQueue\Driver\DriverFactory;
use Hyperf\AsyncQueue\Driver\DriverInterface;
use Hyperf\AsyncQueue\JobInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;

/**
 * Class QueueService
 * @package App\Service
 */
class QueueService
{
    /**
 * @var LoggerInterface
 */
    protected $logger;

    /**
     * @var DriverInterface
     */
    protected $driver;


    public function __construct(DriverFactory $driverFactory)
    {
        $this->driver = $driverFactory->get('default');
        $this->logger = ApplicationContext::getContainer()->get(LoggerFactory::class)->get('queue');
    }

    /**
     * 生产消息.
     * @param JobInterface $job 实例化对象job
     * @param int $delay 延时时间 单位秒
     */
    public function push(JobInterface $job, int $delay = 0): bool
    {
        if (!($job instanceof JobInterface)) {
            return false;
        }
        return $this->driver->push($job, $delay);
    }

    /**
     * @AsyncQueueMessage(pool="other", delay=10)
     */
    public function testJob(array $params)
    {
        sleep(2);
        echo date('Y-m-d H:i:s') . " exec testJob function start\r\n";
        for($i=0; $i<10; $i++){
            co(function() use ($i){
                echo "exec $i\r\n";
            });
        }

        $this->logger->info(sprintf("testJob function params: %s\r\n", json_encode($params)));
        echo date('Y-m-d H:i:s') . " exec testJob function end\r\n";

        return true;
    }

}